package com.app.mall.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:过滤器
 * @Author: zengtaiyang
 * @Date: 2021/4/13 17:49
 * @Version: 1.0
 */
@Component
public class GateWayFilter implements GlobalFilter, Ordered {

    private static List<String> blackList = new ArrayList<>();

    static {
        blackList.add("111.111.111.111");
    }

    String message = "请求被禁止";

    /**
     * 模拟黑名单: 获取客户端ip,判断是否存在黑名单总,存在则拒绝访问,不存在则放行
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取客户端IP
        String ip = request.getRemoteAddress().getHostString();
        //判断是否存在于黑名单
        if (blackList.contains(ip)) {
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//未经授权
            DataBuffer wrap = response.bufferFactory().wrap(message.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //合法请求,放行,执行后续请求
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
